package com.business.web.spring;


import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.common.utils.DateUtil;
import com.common.utils.HandExcelleFile;
import com.common.utils.SystemConstants;
import org.apache.log4j.Logger;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

//import com.workflow.WorkFlowUtils;
import com.common.db.JsonVO;
import com.common.db.Pg;
import com.common.utils.BeanUtils;
import com.system.service.LxConstans;
import com.business.domain.T_goods;
import com.business.domain.T_order;
import com.business.domain.T_order_goods;
import com.business.service.T_goodsService;
//import com.business.mapper.T_orderMapper;
import com.business.service.T_orderService;
import com.business.service.T_order_goodsService;

@Controller
@RequestMapping("/t_order")

public class T_orderController
{
	private static Logger log = Logger.getLogger(T_orderController.class.getName());

	@Resource
    private T_orderService t_orderService;
	@Resource
	private T_order_goodsService t_order_goodsService;

	@Resource
    private T_goodsService t_goodsService;

	//@Autowired
	//private WorkFlowUtils workFlowUtils;

	//@Resource
	//private T_orderMapper mapper;
	//private int id;
	//private int[] ids;
	private Pg pg;

	/**
	 * 0、获取 T_order信息列表，并且在列表页面展示
	 * @param response
	 * @return Pg，json格式
	 */
	@RequestMapping("/t_orderDownload")
	//@ResponseBody
	public void t_orderDownload(HttpServletResponse response){

		int pageSize = 10000;
		int startIndex = 0;
		T_order t_order = new T_order();
		List<T_order> findAll = null;
		t_order.setStartNo( startIndex );
		t_order.setPageSize( pageSize );
		t_order.setEndNo( pageSize );
		String sheetName = "礼品领取表"+ DateUtil.getCurrDate();
		String fileName = "导出礼品申请表_"+DateUtil.getCurrDate()+".xls";
		Map<String,Object> excelMap = new HashMap<>();

		try{
			//1.设置Excel表头
			List<String> headerList = new ArrayList<>();
			headerList.add("订单id");
			headerList.add("卡号");
			headerList.add("密码");
			headerList.add("礼品名称");
			headerList.add("收件人");
			headerList.add("收件人电话");
			headerList.add("收件地址");
			headerList.add("领取时间");
			headerList.add("领取ip");
			headerList.add("运单号");
			headerList.add("更新人");
			headerList.add("更新时间");
			excelMap.put("header",headerList);

			//2.是否需要生成序号，序号从1开始(true-生成序号 false-不生成序)
			excelMap.put("isSerial",false);

			//3.sheet名
			excelMap.put("sheetName",sheetName);

			//4.需要放入Excel中的数据
			Map<String,Object> map = new HashMap<>();
			//map.put("gender","男");
			List<T_order> rows  = t_orderService.findAll(t_order);
			List<List<String>> data= new ArrayList<>();
			//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for (T_order t_order1:rows){
				//所有的数据顺序必须和表头一一对应
				//list存放每一行的数据（让所有的数据类型都转换成String，这样就无需担心Excel表格中数据不对）
				List<String> list = new ArrayList<>();
				list.add(String.valueOf(t_order1.getOrder_id()));
				list.add(String.valueOf(t_order1.getMomo1()));
				list.add(String.valueOf(t_order1.getMemo2()));
				list.add(String.valueOf(t_order1.getOrder_info()));
				list.add(String.valueOf(t_order1.getBuyer()));

				list.add(String.valueOf(t_order1.getExt1()));
				list.add(String.valueOf(t_order1.getExt2()));
				list.add(String.valueOf(t_order1.getCreattime()));
				list.add(String.valueOf(nullToString(t_order1.getCreater())));
				list.add(String.valueOf(nullToString(t_order1.getMemo3())));

				list.add(String.valueOf(nullToString(t_order1.getUpdater())));
				list.add(String.valueOf(nullToString(t_order1.getUpdatetime())));
				//list.add(String.valueOf(format.format(t_order1.getCreateTime())));
				//data存放全部的数据
				data.add(list);
			}
			excelMap.put("data",data);

			//调用下载excel方法；
			HandExcelleFile.downloadExcel(excelMap, fileName, response );

		} catch (Exception e) {
			e.printStackTrace();
			log.error("------query t_orderList error:"+e);
		}

		//return "down excel";
	}

	public String nullToString(Object obj){
		if(null != obj) {
			return obj.toString();
		}
		else{
			return "";
		}
	}
	/**
	 * 1、获取 T_order信息列表，并且在列表页面展示
	 * @param request
	 * @return Pg，json格式
	 */
	@RequestMapping("/getAllT_order")
	@ResponseBody
	public Pg getAllT_order(HttpServletRequest request){
        int pageSize = 10;
        int startIndex = 0;
        T_order t_order = new T_order();
        try{
	        if(request.getParameter("pageSize")!=null){
	        	pageSize = BeanUtils.stringToInt("pageSizeFlag", request.getParameter("pageSize"));
	        }
	        if(request.getParameter("startIndex")!=null){
	            startIndex = BeanUtils.stringToInt("startIndexFlag", request.getParameter("startIndex"));
	        }
	        if(request.getParameter("process_code")!=null){ //取得动作流 流程英文名称，后台查询数据关联使用
	        	t_order.setProcess_code(request.getParameter("process_code"));
	        }
			if(request.getParameter("order_no")!=null&&!"".equals(request.getParameter("order_no"))){
	        	t_order.setOrder_no(request.getParameter("order_no"));
	        }
			if(request.getParameter("buyer")!=null&&!"".equals(request.getParameter("buyer"))){
	        	t_order.setBuyer(request.getParameter("buyer"));
	        }
			if(request.getParameter("order_info")!=null&&!"".equals(request.getParameter("order_info"))){
	        	t_order.setOrder_info(request.getParameter("order_info"));
	        }
			if(request.getParameter("creater")!=null&&!"".equals(request.getParameter("creater"))){
	        	t_order.setCreater(request.getParameter("creater"));
	        }
			if(request.getParameter("creattime")!=null&&!"".equals(request.getParameter("creattime"))){
	        	t_order.setCreattime(request.getParameter("creattime"));
	        }
			if(request.getParameter("updater")!=null&&!"".equals(request.getParameter("updater"))){
	        	t_order.setUpdater(request.getParameter("updater"));
	        }
			if(request.getParameter("updatetime")!=null&&!"".equals(request.getParameter("updatetime"))){
	        	t_order.setUpdatetime(request.getParameter("updatetime"));
	        }
			if(request.getParameter("ext1")!=null&&!"".equals(request.getParameter("ext1"))){
	        	t_order.setExt1(request.getParameter("ext1"));
	        }
			if(request.getParameter("ext2")!=null&&!"".equals(request.getParameter("ext2"))){
	        	t_order.setExt2(request.getParameter("ext2"));
	        }
			if(request.getParameter("ext3")!=null&&!"".equals(request.getParameter("ext3"))){
	        	t_order.setExt3(request.getParameter("ext3"));
	        }
			if(request.getParameter("status")!=null&&!"".equals(request.getParameter("status"))){
	        	t_order.setStatus(request.getParameter("status"));
	        }
			if(request.getParameter("momo1")!=null&&!"".equals(request.getParameter("momo1"))){
	        	t_order.setMomo1(request.getParameter("momo1"));
	        }
			if(request.getParameter("memo2")!=null&&!"".equals(request.getParameter("memo2"))){
	        	t_order.setMemo2(request.getParameter("memo2"));
	        }
			if(request.getParameter("memo3")!=null&&!"".equals(request.getParameter("memo3"))){
	        	t_order.setMemo3(request.getParameter("memo3"));
	        }
			if(request.getParameter("memo4")!=null&&!"".equals(request.getParameter("memo4"))){
	        	t_order.setMemo4(request.getParameter("memo4"));
	        }
			if(request.getParameter("memo5")!=null&&!"".equals(request.getParameter("memo5"))){
	        	t_order.setMemo5(request.getParameter("memo5"));
	        }
			if(request.getParameter("momo6")!=null&&!"".equals(request.getParameter("momo6"))){
				t_order.setMemo6(request.getParameter("momo6"));
			}
			if(request.getParameter("memo7")!=null&&!"".equals(request.getParameter("memo7"))){
				t_order.setMemo7(request.getParameter("memo7"));
			}
			if(request.getParameter("memo8")!=null&&!"".equals(request.getParameter("memo8"))){
				t_order.setMemo8(request.getParameter("memo8"));
			}
			if(request.getParameter("memo9")!=null&&!"".equals(request.getParameter("memo9"))){
				t_order.setMemo9(request.getParameter("memo9"));
			}
			if(request.getParameter("memo10")!=null&&!"".equals(request.getParameter("memo10"))){
				t_order.setMemo10(request.getParameter("memo10"));
			}
			if(request.getParameter("biztype")!=null&&!"".equals(request.getParameter("biztype"))){
				t_order.setBiztype(request.getParameter("biztype"));
			}

      	    if(request.getParameter("order_id")!=null&&!"".equals(request.getParameter("order_id"))){
	        	t_order.setOrder_id(new Integer(request.getParameter("order_id")));
	        }

	        if(request.getParameter("startdate")!=null&&!"".equals(request.getParameter("startdate"))){
	        	t_order.setStartdate(request.getParameter("startdate"));
	        }
	        if(request.getParameter("enddate")!=null&&!"".equals(request.getParameter("enddate"))){
	        	t_order.setEnddate(request.getParameter("enddate"));
	        }
	        t_order.setStartNo( startIndex );
	        t_order.setPageSize( pageSize );
	        t_order.setEndNo( pageSize );
	    	List<T_order> findAll = t_orderService.findAll(t_order);
	        int totalCount = t_orderService.findCountAll(t_order);
	       	pg = new Pg(findAll, totalCount, pageSize, startIndex);
	       	request.setAttribute("t_orderList", findAll);
		    request.setAttribute("pg", pg);
	    } catch (Exception e) {
			e.printStackTrace();
			log.error("------query t_orderList error:"+e);
		}

		return pg;
	}

	/**
	 * 2、1\新增保存  T_order信息并且返回成功或者失败信息json格式结果如：result:[success/error]
	 * @param t_order
	 * @param request
	 * @return
	 */
	@RequestMapping("/saveT_order")
	@ResponseBody
	public JsonVO saveT_order(T_order t_order, HttpServletRequest request,HttpServletResponse response, RedirectAttributes redirectAttributes){
		JsonVO vo = new JsonVO();
		vo.setResult("error");
		vo.setJieguo(false);
		//如果有特殊需求，需要将json对象值转成java实体对象属性值
		//登录整合后，修改为真实的登录账号公司id；
		t_order.setCreattime(com.common.utils.DateUtil.getCurrDateTimeStand());
		t_order.setStatus("0"); //已下单待发货

		int pageSize = 10;
		int startIndex = 0;
		//查询该卡号密码是否存在，如果不存在，则提示卡号密码不存在；
		T_goods t_goods =new T_goods();
		t_goods.setGoods_info(t_order.getMomo1()+","+t_order.getMemo2());
		t_goods.setStartNo( startIndex );
		t_goods.setPageSize( pageSize );
		t_goods.setEndNo( pageSize );
		t_goods.setCreater(request.getRemoteAddr());
		T_goods goodstemp = null;

		List<T_goods> list = t_goodsService.findAll(t_goods);
		if(list.size()==1){
			goodstemp = (T_goods)list.get(0) ;
			//如果已经领用过，则提示已经申领过了；
			if("1".equals(goodstemp.getStatus())){ //status==0或者空为“未使用”，1==“已使用”；
				vo.setInfo("卡号:"+t_order.getMomo1()+",密码:"+t_order.getMemo2()+"已经领取礼品，不能重复领取！");
				log.error("------卡号:"+t_order.getMomo1()+",密码:"+t_order.getMemo2()+"已经领取礼品，不能重复领取！");
				return vo;
			}else{
				log.error("------卡号="+t_order.getMomo1()+",密码="+t_order.getMemo2()+"未领取！");
				vo.setInfo("卡号="+t_order.getMomo1()+",密码="+t_order.getMemo2()+"未领取！");
			}
		}else{
			log.error("------卡号:"+t_order.getMomo1()+",密码:"+t_order.getMemo2()+"不存在，请输入正确的卡号密码！");
			vo.setInfo("卡号:"+t_order.getMomo1()+",密码:"+t_order.getMemo2()+"不存在，请输入正确的卡号密码！");
			return vo;
		}

		//卡号密码正确且为领用
		if(t_orderService.save(t_order)>0){
	        vo.setResult("success");
	        vo.setJieguo(true);
	        //更新goods信息，状态为已领用，status=1；
			goodstemp.setStatus("1");
			int upflag = t_goodsService.update(goodstemp);
			log.error("------更新goods信息卡号:"+t_order.getMomo1()+",密码:"+t_order.getMemo2()+"status=1 数据库行返回值="+upflag);
		}

		return vo;
	}
	/**
	 * 2、2\新增保存  T_order信息并且返回成功或者失败信息json格式结果如：result:[success/error]
	 * @param t_order
	 * @param request
	 * @return
	 */
	@RequestMapping("/saveT_orderOld")
	//@ResponseBody
	public String saveT_orderOld(T_order t_order, HttpServletRequest request,HttpServletResponse response, RedirectAttributes redirectAttributes){
		JsonVO vo = new JsonVO();
		vo.setResult("error");
		vo.setJieguo(false);
		//如果有特殊需求，需要将json对象值转成java实体对象属性值
		//登录整合后，修改为真实的登录账号公司id；
		t_order.setBuyer(""+request.getSession().getAttribute(LxConstans.SESSION_USER_COMPANY_ID));
		t_order.setOrder_no("");
		t_order.setCreater(""+request.getSession().getAttribute(LxConstans.SESSION_USER_CUSTOMER_ID));
		t_order.setCreattime(com.common.utils.DateUtil.getCurrDateTimeStand());
		t_order.setStatus("0"); //已下单待发货

		if(t_orderService.save(t_order)>0){
			vo.setResult("success");
			vo.setJieguo(true);
			//更新购物车中货物订单号为 t_order的order_id;
			T_order_goods goods = new T_order_goods();
			String buyer = ""+request.getSession().getAttribute(LxConstans.SESSION_USER_COMPANY_ID);
			goods.setBuyer(buyer);
			goods.setOrder_id(t_order.getOrder_id());
			goods.setStatus("0"); //0：已下单；1：已确认发货
			//对同一个买方企业购物车中的商品全部更新为订单号，状态为已下单，
			t_order_goodsService.updateByBuyer(goods);

			//对商品销售熟练进行更新增加；对商品库存数量进行更新减少
			T_order_goods temp_order_goods = new T_order_goods();
			temp_order_goods.setOrder_id(t_order.getOrder_id());
			temp_order_goods.setStartNo(0);
			temp_order_goods.setEndNo(100000);
			List list = t_order_goodsService.findAll(temp_order_goods);
			Iterator it = list.iterator();
			while(it.hasNext()){
				T_order_goods tod = (T_order_goods)it.next();
				T_goods tg = new T_goods();
				tg.setGoods_id(tod.getGoods_id());
				tg.setStartNo(0);
				tg.setEndNo(100000);
				T_goods oldtg= t_goodsService.findById(tg);
				oldtg.setSalenum(oldtg.getSalenum() + tod.getGood_num().intValue()); //更新销售数量 +
				oldtg.setNum(oldtg.getNum() - tod.getGood_num().intValue()); //更新库存数量 -
				t_goodsService.update(oldtg);
			}
		}

		String tempBathPath= request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort() +""+ request.getContextPath()+"/";
		try {
			redirectAttributes.addAttribute("order_id", t_order.getOrder_id());

			//response.sendRedirect(tempBathPath+"caigouThree");
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
		}

		return "redirect:"+tempBathPath+"caigouThree";
	}

	/**
	 * 3、修改T_order信息并且返回成功或者失败信息json格式结果如：result:[success/error]
	 * @param t_order
	 * @param request
	 * @return JsonVO
	 */
	@RequestMapping("/updateT_order")
	@ResponseBody
	public JsonVO updateT_order(T_order t_order, HttpServletRequest request){
		JsonVO vo = new JsonVO();
		vo.setResult("error");
		vo.setJieguo(false);
		//如果有特殊值需要处理，在此处手工转换
		//T_order t_orderTemp = t_orderService.findById(t_order);
		//t_orderTemp.setXXX(t_order.getXXX());
		//if(t_orderService.update(t_orderTemp)){
		t_order.setUpdatetime(DateUtil.getCurrDateTimeStand());
		t_order.setUpdater(request.getSession().getAttribute(SystemConstants.SESSIONNAME).toString());
		if(t_orderService.update(t_order)>0){
	        vo.setResult("success");
	        vo.setJieguo(true);
		}
		return vo;
	}

	/**
	 * 3、2修改T_order信息并且返回成功或者失败信息json格式结果如：result:[success/error]
	 * @param t_order
	 * @param request
	 * @return JsonVO
	 */
	@RequestMapping("/updateT_orderGH")
	@ResponseBody
	public JsonVO updateT_orderGH(T_order t_order, HttpServletRequest request){
		JsonVO vo = new JsonVO();
		vo.setResult("error");
		vo.setJieguo(false);
		//如果有特殊值需要处理，在此处手工转换
		String old_order_no = t_order.getOrder_no();

		//设置更新借用出库信息
		t_order.setUpdatetime(DateUtil.getCurrDateTimeStand());
		t_order.setUpdater(request.getSession().getAttribute(SystemConstants.SESSIONNAME).toString());
		//t_order.setBiztype("1"); //1：已归还；已改为 OA 、wuye
		t_order.setMemo10("已归还"); //未归还；已归还；
		t_order.setMemo6(t_order.getMemo6()); //归还人
		t_order.setMemo7(t_order.getMemo7()); //归还时间
		t_orderService.update(t_order);
		//设置新增归还记录信息
		t_order.setStatus("1");  //0：借用记录；1:归还记录；
		t_order.setOrder_no(t_order.getOrder_id().toString()); //设置是对那笔借用记录进行归还，生成一条归还记录

		if(t_orderService.save(t_order)>0){
			T_order_goods t_order_goods = new T_order_goods();
			t_order_goods.setOrder_goods_id(new Integer(old_order_no) ); //要用借用时存储的 库存id；找到对应库存记录，增加归还库存数量并且更新到数据库；
			t_order_goods = t_order_goodsService.findById(t_order_goods);
			t_order_goods.setGood_num( t_order.getAmount().doubleValue() + t_order_goods.getGood_num() );  //库存增加归还数量；
			int retval = t_order_goodsService.update(t_order_goods);
			if(retval>0){
				vo.setResult("success");
				vo.setJieguo(true);
			}else{
				log.error("------归还借用物料时，库存增加失败， t_order_goods  goods_num 增加归还数量="+t_order.getAmount()+"失败！");
			}
		}
		return vo;
	}

	/**
	 * 4、根据id查询T_order单个信息并显示在修改页面
	 * @param id
	 * @param request
	 * @return T_order json格式字符串
	 */
	@RequestMapping("/getT_order")
	@ResponseBody
	public T_order getT_order(Integer id,HttpServletRequest request){
		T_order t_order = new T_order();
		t_order.setOrder_id(id);
		return t_orderService.findById(t_order);
	}

	/**
	 * 5、删除T_order根据id
	 * @param id
	 * @param request
	 * @param response
	 * return JsonVO ：json格式字符串
	 */
	@RequestMapping("/delT_order")
	@ResponseBody
	public JsonVO delT_order(Integer id,HttpServletRequest request,HttpServletResponse response){
        JsonVO vo = new JsonVO();
		vo.setResult("error");
		vo.setJieguo(false);

		T_order t_order = new T_order();
		t_order.setOrder_id(id);

		if(t_orderService.delete(t_order)>0){
			vo.setResult("success");
	        vo.setJieguo(true);
		}
		return vo;
	}

	/**
	 * 6、跳转到t_order/toT_orderList查询所有数据页面
	 *  return /WEB-INF/views/business/t_order/t_orderList.jsp
	 */
    @RequestMapping(value = "/toT_orderList")
    public String toT_orderList() {
    	log.debug("------跳转到/WEB-INF/views/business/t_order/t_orderList.jsp------");
        return "business/t_order/t_orderList";
    }

	@RequestMapping(value = "/toT_orderListOA")
	public String toT_orderListOA() {
		log.debug("------跳转到/WEB-INF/views/business/t_order/t_orderListOA.jsp------");
		return "business/t_order/t_orderListOA";
	}

	/**
	 * 6、2跳转到t_order/toT_orderList查询所有数据页面
	 *  return /WEB-INF/views/business/t_order/t_orderListInIn.jsp
	 */
	@RequestMapping(value = "/toT_orderListIn")
	public String toT_orderListIn() {
		log.debug("------跳转到/WEB-INF/views/business/t_order/t_orderListIn.jsp------");
		return "business/t_order/t_orderListIn";
	}

	@RequestMapping(value = "/toT_orderListInOA")
	public String toT_orderListInOA() {
		log.debug("------跳转到/WEB-INF/views/business/t_order/t_orderListInOA.jsp------");
		return "business/t_order/t_orderListInOA";
	}
	/**
	 * 6、3跳转到t_order/toT_orderList查询所有数据页面
	 *  return /WEB-INF/views/business/t_order/t_orderListOut.jsp
	 */
	@RequestMapping(value = "/toT_orderListOut")
	public String toT_orderListOut() {
		log.debug("------跳转到/WEB-INF/views/business/t_order/t_orderListOut.jsp------");
		return "business/t_order/t_orderListOut";
	}

	@RequestMapping(value = "/toT_orderListOutOA")
	public String toT_orderListOutOA() {
		log.debug("------跳转到/WEB-INF/views/business/t_order/t_orderListOutOA.jsp------");
		return "business/t_order/t_orderListOutOA";
	}
	/**
	 * 7、新增、修改、详情页面t_order/toT_orderCurd跳转
     * business/t_order/T_orderCurd.jsp
	 */
    @RequestMapping(value = "/toT_orderCurd")
    public String toT_orderCurd() {
    	log.debug("------跳转到/WEB-INF/views/business/t_order/t_orderCurd.jsp------");
        return "business/t_order/t_orderCurd";
    }

    /**
	 * 8、批量删除T_order根据主键id
	 * 是否要实现批量删除，待考虑，基本上用途不大
	 * @param id
	 * @param request
	 * @param response
	@RequestMapping("/delT_orderBatch")
	public String delT_orderBatch(HttpServletRequest request,HttpServletResponse response){
		String[] ids = request.getParameterValues("ids");
		System.out.println("------ids="+ids);
		T_order t_order = new T_order();
		int j=0;
		for(int i =0;i< ids.length;i++){
			j++;
			log.error("------ids[i]="+ids[i]);
			t_order.setOrder_id(new Integer(ids[i]).intValue());
			t_orderService.delete(t_order);
		}
		if(j==ids.length){
			log.debug("------t_order批量删除成功！------");
		}else{
			log.error("------t_order批量删除部分成功！部分失败！------");
		}

		return "redirect:/t_order/getAllT_order";
	}
*/



}









